package com.mmc.delay.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;

public class RedisLockHelper {

    private RedisTemplate redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(RedisLockHelper.class);

    public RedisLockHelper(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //lock script
    private static final String lockScript = " if redis.call('setnx',KEYS[1],ARGV[1]) == 1 " +
            " then redis.call('expire',KEYS[1],ARGV[2]) " +
            " return 1 " +
            " else return 0 end ";

    //unlock script
    private static final String unlockScript = " if redis.call('get',KEYS[1]) == ARGV[1] " +
            " then return redis.call('del',KEYS[1]) " +
            " else return 0 end ";

    /**
     * 加锁
     * @param key
     * @param value
     * @param second 锁过期时间
     * @return
     */
    public boolean lock(String key,String value,Long second){
        DefaultRedisScript<Boolean> script = new DefaultRedisScript<>();
        script.setScriptText(lockScript);
        script.setResultType(Boolean.class);
        Boolean result = (Boolean) redisTemplate.execute(script, Collections.singletonList(key), value, second);
        return result;
    }





    /**
     * 解锁
     * @param key
     * @param value
     * @return
     */
    public boolean unlock(String key,String value){
        DefaultRedisScript<Boolean> script = new DefaultRedisScript<>();
        script.setScriptText(unlockScript);
        script.setResultType(Boolean.class);
        Boolean result = (Boolean) redisTemplate.execute(script, Collections.singletonList(key), value);
        return result;
    }
}
